package com.common.core.domain;

import com.common.core.enums.ResultCode;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class R<T> {
    private int code;
    private String msg;
    private T data;

    // 这里使用了工厂模式
    public static <T> R<T> success() {
        return assembleResult(null, ResultCode.SUCCESS);
    }
    public static <T> R<T> success(T data) {
        return assembleResult(data, ResultCode.SUCCESS);
    }
    public static <T> R<T> failed() {
        return assembleResult(null, ResultCode.FAILED);
    }
    public static <T> R<T> failed(int code, String msg) {
        return assembleResult(code, msg, null);
    }
    // 错误类型有多种，使用枚举类
    public static <T> R<T> failed(ResultCode resultCode) {
        return assembleResult(null, resultCode);
    }

    private static <T> R<T> assembleResult(T data, ResultCode resultCode) {
        R<T> result = new R<T>();
        result.setCode(resultCode.getCode());
        result.setData(data);
        result.setMsg(resultCode.getMsg());
        return result;
    }
    private static <T> R<T> assembleResult(int code, String msg, T data) {
        R<T> result = new R<T>();
        result.setCode(code);
        result.setData(data);
        result.setMsg(msg);
        return result;
    }
}
